package com.tiger.utils;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

public class Redis {
	
	private final static boolean REDIS_AVAILABLE = Conf.getBoolean("redis.available");
	private final static StringRedisTemplate TEMPLATE = Context.getBean(StringRedisTemplate.class);

	public static void set(String key, String t) {
		if (!REDIS_AVAILABLE) {
			return;
		}
		ValueOperations<String, String> valueOper = TEMPLATE.opsForValue();
		valueOper.set(key, t);
	}
	
	public static void setex(String key, String t, int expireHours) {
		if (!REDIS_AVAILABLE) {
			return;
		}
		ValueOperations<String, String> valueOper = TEMPLATE.opsForValue();
		valueOper.set(key, t);
		TEMPLATE.expire(key, expireHours, TimeUnit.HOURS);
	}
	
	public static void setex(String key, String t, long timeout, TimeUnit unit) {
		if (!REDIS_AVAILABLE) {
			return;
		}
		ValueOperations<String, String> valueOper = TEMPLATE.opsForValue();
		valueOper.set(key, t);
		TEMPLATE.expire(key, timeout, unit);
	}

	public static void publish(String key, String t) {
		if (!REDIS_AVAILABLE) {
			return;
		}
		TEMPLATE.convertAndSend(key, t);
	}
	
	public static String get(String key) {
		if (!REDIS_AVAILABLE) {
			return null;
		}
		ValueOperations<String, String> valueOper = TEMPLATE.opsForValue();
		String value = valueOper.get(key);
		return value;
	}
	public static void delete(String key){
		if (REDIS_AVAILABLE) {
			TEMPLATE.delete(key);
		}
	}
}